package com.xzq.erp.ai.config;

import com.xzq.erp.ai.constants.ChatConstants;
import com.xzq.erp.ai.memory.RedisChatMemory;
import com.xzq.erp.ai.memory.RedisChatMemoryRepository;
import com.xzq.erp.ai.tools.OrderTools;
import com.xzq.erp.ai.tools.RoleAndPermissionTools;
import com.xzq.erp.constants.PromptConstants;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfiguration {

    @Bean
    public RedisChatMemoryRepository redisChatMemoryRepository() {
        return new RedisChatMemoryRepository();
    }

    @Bean
    public ChatMemory chatMemory(RedisChatMemoryRepository redisChatMemoryRepository) {
        return RedisChatMemory.builder()
                .chatMemoryRepository(redisChatMemoryRepository)
                .maxMessages(ChatConstants.MAX_CHAT_HISTORY_MESSAGE_COUNT)
                .build();
    }

    @Bean
    public ChatClient chatClient(OpenAiChatModel model, ChatMemory chatMemory, RoleAndPermissionTools roleAndPermissionTools, OrderTools orderTools) {
        return ChatClient
                .builder(model)
                .defaultSystem(PromptConstants.SYSTEM_PROMPT)
                .defaultAdvisors(new SimpleLoggerAdvisor()) // 日志记录
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) // 添加会话记忆
                .defaultTools(roleAndPermissionTools,orderTools)
                .build();
    }
}